package org.dfl.plugin;

import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.dfl.messages.Messages;
import org.eclipse.jface.resource.ImageDescriptor;

/**
 * processor helper (like from taverna) to load images needed in a palette tree
 * @author Piotr Wlodarczyk
 *
 */
@SuppressWarnings("unchecked") //$NON-NLS-1$
public class DflProcessorHelper {
	private static Logger LOG = Logger.getLogger(DflProcessorHelper.class);
	@SuppressWarnings("unchecked") //$NON-NLS-1$
	static Map iconForTagName = null;
	static Properties tavernaProperties = null;
	static ImageDescriptor unknownProcessorIcon;

	static {
		try {
			// Get the classloader for this class
			ClassLoader loader = DflProcessorHelper.class.getClassLoader();
			if (loader == null) {
				loader = Thread.currentThread().getContextClassLoader();
			}
			// Load the 'unknown processor' image icon
			unknownProcessorIcon =DflPlugin.getImageDescriptor("icons/processors/unknownprocessor.png"); //$NON-NLS-1$
			// Load up the values from any taverna.properties files located
			// by the class resource loader.
			Enumeration en = loader.getResources("taverna.properties"); //$NON-NLS-1$
			tavernaProperties = new Properties();
			while (en.hasMoreElements()) {
				URL resourceURL = (URL) en.nextElement();
				LOG.info(Messages.DflProcessorHelper_4 + resourceURL.toString());
				tavernaProperties.load(resourceURL.openStream());
			}
		} catch (Exception e) {
			LOG.fatal(Messages.DflProcessorHelper_5, e);
			// Don't exit, as this hides the stack trace etc!
			// System.exit(1);
		}
	}

	/**
	 * Given a tag name, return the preferred image icon for that tag.
	 */
	public static ImageDescriptor getIconForTagName(String tagName) {
		if (iconForTagName == null) {
			// Initialise the icon store
			iconForTagName = new HashMap();
			for (Iterator i = tavernaProperties.keySet().iterator(); i
					.hasNext();) {
				String key = (String) i.next();
				String value = tavernaProperties.getProperty(key);
				String[] keyElements = key.split("\\."); //$NON-NLS-1$
				if (keyElements.length == 4
						&& keyElements[1].equals("processor")) { //$NON-NLS-1$
					String loadTagName = keyElements[2];
					// Form : taverna.processor.<TAGNAME>.icon =
					// <RENDERINGHINT_ICON>
					if (keyElements[3].equals("icon")) { //$NON-NLS-1$
						// Fetch resource icon...
						iconForTagName.put(loadTagName, DflPlugin.getImageDescriptor("icons/processors/"+FilenameUtils.getName(value))); //$NON-NLS-1$
					}
				}
			}
		}

		// LOG.debug("Request for icon for : "+tagName);
		ImageDescriptor icon = (ImageDescriptor) iconForTagName.get(tagName);
		if (icon == null) {
			return unknownProcessorIcon;
		}
		return icon;
	}
}
